﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ComponentModel;
using System.Globalization;
using System.Xml.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Advertising.Mobile.UI;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using MarkHeath.StarRating;
using OnlineVideos.ViewModels;
using Common.Library;
using OnlineVideos.Library;
using OnlineVideos.UI;
using OnlineVideos.Common;
using OnlineVideos.View_Models;
using OnlineVideos.Entities;
using Microsoft.Phone.BackgroundAudio;
using System.Windows.Threading;
//using OnlineVideos.Game;
//using MyToolkit.Multimedia;
using OnlineVideos.Data;
using OnlineVideos.Utilities;
using Common.Utilities;
using PicasaMobileInterface;
using System.Threading.Tasks;

namespace OnlineVideos.Views
{
    public partial class ShowDetails : PhoneApplicationPage
    {
        #region Global



        string navigationvalue = string.Empty;
        string pivotindex = string.Empty;
        PivotItem currentItem = default(PivotItem);
        bool appbarvisible = true;
        string background = "0";
        string chapter = string.Empty;
        public DispatcherTimer storyboardtimer;
        #endregion

        #region Private Methods
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(MainGrid, adstaSongs, 1);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }

        private void LoadPivotThemes(long ShowID)
        {
            try
            {
            pvtMainDetails.Background = ShowDetail.LoadShowPivotBackground(ShowID);
            if (!ShowCastManager.ShowGamePivot(AppSettings.ShowID))
            {
                pvtMainDetails.Items.Remove(gamepivot);
            }
            if (ResourceHelper.AppName == Apps.Fitness_Programs.ToString() || ResourceHelper.AppName == Apps.World_Dance.ToString())
            {
                pvtitmSongs.Header = "";
                pvtMainDetails.Items.Remove(pvtitmCast);
            }
            if (ResourceHelper.AppName == "Yoga_&_Health")
            {
                pvtitmCast.Header = "asanas";
                pvtMainDetails.Items.Remove(gamepivot);
                pvtMainDetails.SelectedIndex = 1;
            }
            else
            {
                pvtitmCast.Header = "characters";
            }
            Loaded += new RoutedEventHandler(PhoneApplicationPage_Loaded);
        }
            catch (Exception ex)
            {

                 Exceptions.SaveOrSendExceptions("Exception in LoadPivotThemes Method In ShowDetails.cs file", ex);
            }
        }
      


        #endregion

        #region Initialization

        public ShowDetails()
        {
            try
            {
            InitializeComponent();

            if (AppSettings.ShowID != "0")
            {
                LoadPivotThemes(AppSettings.ShowUniqueID);
                //TODO: Save title also in settings or pass through query string
                tblkVideosTitle.Text = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID).Title;
                background = "1";
            }


          
            Loaded += new RoutedEventHandler(PhoneApplicationPage_Loaded);
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in ShowDetails Method In ShowDetails.cs file", ex);
            }
          
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

            try
            {
                FlurryWP8SDK.Api.LogEvent("ShowDetails Page", true);
            //performanceProgressBar.IsIndeterminate = true;
            LoadAds();
            int showid = AppSettings.ShowUniqueID;
            string sharedstatus = Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.ShareStatus;
            if (sharedstatus == "Shared To Blog")
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Shared)";
            else
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Not Shared)";
            performanceProgressBar.IsIndeterminate = true;

            string id = "";
            if (NavigationContext.QueryString.TryGetValue("id", out id))
                AppSettings.ShowID = id;

            if (background == "0")
            {
                LoadPivotThemes(AppSettings.ShowUniqueID);
                tblkVideosTitle.Text = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID).Title;
            }
            performanceProgressBar.IsIndeterminate = false;
            PageHelper.RemoveEntryFromBackStack("ShowDetails");
        }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In ShowDetails.cs file", ex);
            }
        }
        
        #endregion

       
        #region Events

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

            try
            {
               
                FlurryWP8SDK.Api.LogPageView();
            int showid = AppSettings.ShowUniqueID;
            if (Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync().Result.Status != "Custom")
            {
                this.ApplicationBar.IsVisible = false;
                appbarvisible = false;
            }
            else
            {
                this.ApplicationBar.IsVisible = true;
            }
            if (NavigationContext.QueryString.TryGetValue("navigationvalue", out navigationvalue))
            {

                if (navigationvalue == "1")
                {
                    if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))
                        pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                    Constants.navigationvalue++;
                }
                else
                {
                    if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))
                        pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                    Constants.navigationvalue--;
                }
                while (NavigationService.BackStack.Count() > 1)
                {
                    if (!NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("ShowDetails"))
                    {
                        NavigationService.RemoveBackEntry();
                    }
                    else
                    {
                        NavigationService.RemoveBackEntry();
                        break;
                    }
                }
            }
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
            {
                AppState.searchtitle = "";
            }
            else
            {
                if (NavigationContext.QueryString.TryGetValue("chapter", out chapter))
                {

                    AppState.searchtitle = chapter;
                }
            }

            if (VideosList.lbxSongsList.IsEnabled == false)
                VideosList.lbxSongsList.IsEnabled = true;
            //YouTube.CancelPlay();
        }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In ShowDetails.cs file", ex);
            }
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {
            AppState.searchtitle = "";
                FlurryWP8SDK.Api.EndTimedEvent("ShowDetails Page");
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom Method In ShowDetails.cs file", ex);
        }
           
        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            //if (YouTube.CancelPlay())
            //    e.Cancel = true;
            
            base.OnBackKeyPress(e);
        }

        private void pvtMainDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
            currentItem = e.AddedItems[0] as PivotItem;
            if (appbarvisible == true)
            {
                if (currentItem != null)
                {
                    if (currentItem.Header.ToString() == "game")
                    {
                        if (this.ApplicationBar.MenuItems.Count == 2)
                            this.ApplicationBar.MenuItems.RemoveAt(1);
                        //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                        //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                    }

                    else
                    {
                        if (this.ApplicationBar.MenuItems.Count < 2)
                        {
                            ApplicationBarMenuItem appBarMenuitem = new ApplicationBarMenuItem("Add" + " " + currentItem.Header.ToString());
                            appBarMenuitem.Click += btnadd_Click_1;
                            this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                        }
                        else
                        {
                            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add" + " " + currentItem.Header.ToString();
                        }
                        //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = true;

                    }
                }
            }
            if (pvtMainDetails.SelectedIndex == 2)
            {
                BackgroundHelper bwhelper = new BackgroundHelper();
                bwhelper.AddBackgroundTask(
                (object s, DoWorkEventArgs a) =>
                {
                    addgame();
                },
                (object s, RunWorkerCompletedEventArgs a) =>
                {

                }
                );

                bwhelper.RunBackgroundWorkers();
                bwhelper.StartScheduledTasks();
            }
            else
            {
                if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
                {
                    if (BackgroundAudioPlayer.Instance != null && BackgroundAudioPlayer.Instance.Track.Source.ToString().Contains("Claps.mp3"))
                    {
                        BackgroundAudioPlayer.Instance.Stop();
                    }
                }
            }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in pvtMainDetails_SelectionChanged Method In ShowDetails.cs file", ex);
            }


        }
        public void addgame()
        {
            try
            {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (!ShowCastManager.ShowGameControl(AppSettings.ShowID))
                {
                    storyboardtimer = new DispatcherTimer();
                    storyboardtimer.Interval = TimeSpan.FromSeconds(2);
                    storyboardtimer.Tick += new EventHandler(storyboardtimer_Tick);
                    storyboardtimer.Start();
                }

            });
            }
            catch (Exception ex)
            {
                
                   Exceptions.SaveOrSendExceptions("Exception in addgame Method In ShowDetails.cs file", ex);
            }

        }

     
        void storyboardtimer_Tick(object sender, EventArgs e)
        {
            try
            {
            if (pvtMainDetails.SelectedIndex == 2)
            {
                if (OnlineVideos.Game.GameInstance.gameopened == false)
                {
                    foreach (OnlineVideos.Game.MemoryCard m in OnlineVideos.Game.GameInstance.stopstoryboard)
                    {
                        m.storyboardfromx = "3";
                        m.storyboardtox = "-3";
                        m.storyboardfromy = "3";
                        m.storyboardtoy = "-3";
                        m.storyboardfromz = "3";
                        m.storyboardtoz = "-3";
                    }
                    storyboardtimer.Stop();
                }
            }
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in storyboardtimer_Tick Method In ShowDetails.cs file", ex);
            }
        }

        #endregion

        private void imgTitle_MouseEnter(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }
        private void btnadd_Click_1(object sender, EventArgs e)
        {
            try
            {
            if ((sender as ApplicationBarMenuItem).Text.Contains("characters"))
            {
                Constants.DownloadTimer.Stop();
                NavigationService.Navigate(new Uri("/Views/AddCast.xaml", UriKind.RelativeOrAbsolute));
            }
            else if ((sender as ApplicationBarMenuItem).Text.Contains("asanas"))
            {
                Constants.DownloadTimer.Stop();
                NavigationService.Navigate(new Uri("/Views/AddCast.xaml", UriKind.RelativeOrAbsolute));
            }
            else
            {


                if ((sender as ApplicationBarMenuItem).Text.Contains("videos"))
                {
                    Constants.DownloadTimer.Stop();
                    Constants.Linkstype = "Songs";
                    NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?language=" + string.Empty, UriKind.Relative));
                }



            }
        }
            catch (Exception ex)
            {

                  Exceptions.SaveOrSendExceptions("Exception in btnadd_Click_1 Method In ShowDetails.cs file", ex);
            }
        }

        private void btnshare_Click_1(object sender, EventArgs e)
        {
            try
            {
            if (NetworkHelper.IsNetworkAvailableForDownloads())
            {
                UploadToBlog upload = new UploadToBlog(AppSettings.ShowUniqueID, page1: this);
            }
        }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in btnshare_Click_1 Method In ShowDetails.cs file", ex);
            }
        }
    }
}
